package com.gomcarter.frameworks.base.converter.jackson;

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.yifeng.repo.base.security.context.manager.RequestContextManager;

import java.util.Map;

/**
 * Created by daibing on 2024/1/22.
 * @deprecated Jackson自定义PropertyNamingStrategy使用需要特别谨慎，避免因为业务使用不当，Jackson缓存机制造成字段精简运行异常
 */
public class TransformerPropertyNamingStrategy extends PropertyNamingStrategy {
    private final Map<String, String> propertyTransformerMapping;

    public TransformerPropertyNamingStrategy(Map<String, String> propertyTransformerMapping) {
        this.propertyTransformerMapping = propertyTransformerMapping;
    }

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        // 待验证
        return super.nameForField(config, field, defaultName);
    }

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        // 当前已经是需要转换返回数据对象的key，就直接开始转换
        if (Boolean.TRUE.equals(RequestContextManager.getTransferRespDataKey())) {
            return propertyTransformerMapping.getOrDefault(defaultName, defaultName);
        }
        // 不需要转换
        return super.nameForGetterMethod(config, method, defaultName);
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        // 当前已经是需要转换返回数据对象的key，就直接开始转换
        if (Boolean.TRUE.equals(RequestContextManager.getTransferRespDataKey())) {
            return propertyTransformerMapping.getOrDefault(defaultName, defaultName);
        }
        // 不需要转换
        return super.nameForSetterMethod(config, method, defaultName);
    }
}
